from flask import Blueprint, render_template, session
from flask_login import login_required, current_user

from applications.common.helper import ModelFilter, Tools
from applications.extensions import db
from applications.models import Record

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')


# 首页
@admin_bp.get('/')
@login_required
def index():
    user = current_user
    return render_template('admin/index.html', user=user)


# 控制台页面
@admin_bp.get('/welcome')
@login_required
def welcome():
    mf = ModelFilter()
    role = session.get("role", [])[0]
    role_id = role[0]
    hospital_no = session.get("hospital_no", 0)
    # 医院只能看自己的
    if role_id == 3:
        mf.exact(field_name="hospital_no", value=hospital_no)
        # 样本数
        ybs = Record.query.filter(mf.get_filter(Record)).count()
        # 下载数
        xzs = db.session.query(db.func.sum(Record.dow_count)).filter(mf.get_filter(Record)).scalar()
    else:
        ybs = Record.query.filter(mf.get_filter(Record)).count()
        xzs = db.session.query(db.func.sum(Record.dow_count)).filter(mf.get_filter(Record)).scalar()
    if xzs is None:
        xzs = 0
    # 获取过去7天的日期
    dd = Tools().day_get()
    list_d = []
    # 7天样本数
    yb_list = {"y": []}
    for obj in dd:
        list_d.append(obj)
    list_week_day = list_d[::-1]
    for obj in list_week_day:
        mff = ModelFilter()
        # 医院只能看自己的
        if role_id == 3:
            mff.exact(field_name="hospital_no", value=hospital_no)
        mff.between(field_name="create_time", value1=obj + ":00:00", value2=obj + ":23:59")
        yb_list['y'].append(Record.query.filter(mff.get_filter(Record)).count())
        del mff
    yb_list['x'] = list_week_day
    return render_template('admin/console/console.html', ybs=ybs, xzs=xzs, yb_list=yb_list)
